package packets.s2cpackets;

import java.util.zip.Deflater;

import packets.SPacket;

public class S0x33 extends SPacket {
	
	/**
	 * Raw constructor. Specify each field and bytearray
	 * explicitly
	 * @param x
	 * @param z
	 */
	public S0x33(int x, int z, boolean groundup, short bitmask, short bitmaskaddarray, byte[] payload) {
		super(0x33);
		
		addInt(x);
		addInt(z);
		
		if(groundup) {
			add((byte) 0x01);
		} else {
			add((byte) 0x00);
		}
		
		addShort(bitmask);
		addShort(bitmaskaddarray);
		
		parsePayload(payload);
		
	}
	
	/**
	 * Parses the payload and adds it to the packet.
	 * The payload is zipped using zlib.
	 * The length of the zip is added to the packet.
	 * 
	 * @param r The payload to parse.
	 */
	private void parsePayload(byte[] r) {
		Deflater compresser = new Deflater();
		compresser.setInput(r);
		compresser.finish();
		
		byte[] chunkblocksP = new byte[9999];
		int numberofbytes = compresser.deflate(chunkblocksP);

		byte[] chunkblocks = new byte[numberofbytes];
		for(int i = 0; i < numberofbytes; i++)
			chunkblocks[i] = chunkblocksP[i];
		
		addInt(numberofbytes);
		addInt(0);	//unused
		add(chunkblocks);
	}
}
